package pl.net.csrv.servlets;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pl.net.csrv.beans.User;
import pl.net.csrv.dao.impl.UserDaoImpl;
import pl.net.csrv.helpers.MD5Helper;

/**
 * Servlet implementation class Logon
 */
@WebServlet("/Logon")
public class Logon extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	UserDaoImpl userDao;
	Logger LOGGER = Logger.getAnonymousLogger();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Logon() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		String md5 = null;
		RequestDispatcher dispatcher;
		User user = null;
		String errorMessage = null;

		if (login != null) {
			user = userDao.findUserByLogin(login);
		} else {
			errorMessage="Specify login!";
		}
		if (user != null) {
			try {
				md5 = MD5Helper.calculateMD5(password);
			} catch (NoSuchAlgorithmException e) {
				LOGGER.log(Level.SEVERE, e.getMessage());
				dispatcher = request.getRequestDispatcher("jsp/errorPage.jsp");
			}
		} else {
			errorMessage = "User doesn't exist!";
		}
		if ((md5 != null) && (md5.equals(user.getEncPasswd()))) {
			dispatcher = request.getRequestDispatcher("jsp/homePage.jsp");
		} else {
			errorMessage = errorMessage == null ? "Wrong password!" : errorMessage;
			request.setAttribute("errorMessage", errorMessage);
//			request.getAttribute("errorMessage");
			dispatcher = request.getRequestDispatcher("index.jsp");
		}
		dispatcher.forward(request, response);
	}

}
